<template>
	<view class="records-container">
		<view class="header">
			<view class="back-btn" @tap="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<view class="title">饮食记录</view>
			<view class="add-btn" @tap="addDietRecord">
				<text class="iconfont icon-add"></text>
			</view>
		</view>
		
		<!-- 日期选择 -->
		<view class="date-selector">
			<view class="date-arrow" @tap="changeDate(-1)">
				<text class="iconfont icon-arrow-left"></text>
			</view>
			<picker 
				mode="date" 
				:value="date" 
				:start="startDate" 
				:end="endDate" 
				@change="dateChange"
				class="date-picker"
			>
				<view class="date-value">{{formattedDate}}</view>
			</picker>
			<view class="date-arrow" @tap="changeDate(1)">
				<text class="iconfont icon-arrow-right"></text>
			</view>
		</view>
		
		<!-- 餐次筛选 -->
		<view class="meal-filter">
			<view 
				class="filter-item" 
				:class="{ active: mealType === 'all' }"
				@tap="selectMealType('all')"
			>
				全部
			</view>
			<view 
				class="filter-item" 
				:class="{ active: mealType === 'breakfast' }"
				@tap="selectMealType('breakfast')"
			>
				早餐
			</view>
			<view 
				class="filter-item" 
				:class="{ active: mealType === 'lunch' }"
				@tap="selectMealType('lunch')"
			>
				午餐
			</view>
			<view 
				class="filter-item" 
				:class="{ active: mealType === 'dinner' }"
				@tap="selectMealType('dinner')"
			>
				晚餐
			</view>
			<view 
				class="filter-item" 
				:class="{ active: mealType === 'snack' }"
				@tap="selectMealType('snack')"
			>
				加餐
			</view>
		</view>
		
		<!-- 营养摄入统计 -->
		<view class="nutrition-stats">
			<view class="stats-item">
				<view class="stats-value">{{ dietStats.calories }}</view>
				<view class="stats-label">卡路里(kcal)</view>
			</view>
			<view class="stats-item">
				<view class="stats-value">{{ dietStats.carbs }}g</view>
				<view class="stats-label">碳水</view>
			</view>
			<view class="stats-item">
				<view class="stats-value">{{ dietStats.protein }}g</view>
				<view class="stats-label">蛋白质</view>
			</view>
			<view class="stats-item">
				<view class="stats-value">{{ dietStats.fat }}g</view>
				<view class="stats-label">脂肪</view>
			</view>
		</view>
		
		<!-- 记录列表 -->
		<view class="records-list" v-if="dietRecords.length > 0">
			<view class="meal-section" v-if="breakfastRecords.length > 0 && (mealType === 'all' || mealType === 'breakfast')">
				<view class="meal-header">
					<view class="meal-title">
						<text class="meal-icon breakfast">早</text>
						<text class="meal-name">早餐</text>
					</view>
					<view class="meal-time">{{breakfastRecords[0].time}}</view>
				</view>
				
				<view class="food-list">
					<view 
						class="food-item" 
						v-for="(item, index) in breakfastRecords" 
						:key="index"
					>
						<image :src="item.food.image || '/static/images/placeholder.png'" mode="aspectFill" class="food-image"></image>
						<view class="food-info">
							<view class="food-name">{{item.food.name}}</view>
							<view class="food-amount">{{item.amount}}{{item.food.unit}}</view>
							<view class="food-nutrition">
								<text class="nutrition-item">{{item.calories}}kcal</text>
								<text class="nutrition-item">碳水{{item.carbs}}g</text>
								<text class="nutrition-item">蛋白质{{item.protein}}g</text>
							</view>
						</view>
						<view class="food-action">
							<view class="delete-btn" @tap.stop="deleteRecord(item)">
								<text class="iconfont icon-delete"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="meal-section" v-if="lunchRecords.length > 0 && (mealType === 'all' || mealType === 'lunch')">
				<view class="meal-header">
					<view class="meal-title">
						<text class="meal-icon lunch">午</text>
						<text class="meal-name">午餐</text>
					</view>
					<view class="meal-time">{{lunchRecords[0].time}}</view>
				</view>
				
				<view class="food-list">
					<view 
						class="food-item" 
						v-for="(item, index) in lunchRecords" 
						:key="index"
					>
						<image :src="item.food.image || '/static/images/placeholder.png'" mode="aspectFill" class="food-image"></image>
						<view class="food-info">
							<view class="food-name">{{item.food.name}}</view>
							<view class="food-amount">{{item.amount}}{{item.food.unit}}</view>
							<view class="food-nutrition">
								<text class="nutrition-item">{{item.calories}}kcal</text>
								<text class="nutrition-item">碳水{{item.carbs}}g</text>
								<text class="nutrition-item">蛋白质{{item.protein}}g</text>
							</view>
						</view>
						<view class="food-action">
							<view class="delete-btn" @tap.stop="deleteRecord(item)">
								<text class="iconfont icon-delete"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="meal-section" v-if="dinnerRecords.length > 0 && (mealType === 'all' || mealType === 'dinner')">
				<view class="meal-header">
					<view class="meal-title">
						<text class="meal-icon dinner">晚</text>
						<text class="meal-name">晚餐</text>
					</view>
					<view class="meal-time">{{dinnerRecords[0].time}}</view>
				</view>
				
				<view class="food-list">
					<view 
						class="food-item" 
						v-for="(item, index) in dinnerRecords" 
						:key="index"
					>
						<image :src="item.food.image || '/static/images/placeholder.png'" mode="aspectFill" class="food-image"></image>
						<view class="food-info">
							<view class="food-name">{{item.food.name}}</view>
							<view class="food-amount">{{item.amount}}{{item.food.unit}}</view>
							<view class="food-nutrition">
								<text class="nutrition-item">{{item.calories}}kcal</text>
								<text class="nutrition-item">碳水{{item.carbs}}g</text>
								<text class="nutrition-item">蛋白质{{item.protein}}g</text>
							</view>
						</view>
						<view class="food-action">
							<view class="delete-btn" @tap.stop="deleteRecord(item)">
								<text class="iconfont icon-delete"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="meal-section" v-if="snackRecords.length > 0 && (mealType === 'all' || mealType === 'snack')">
				<view class="meal-header">
					<view class="meal-title">
						<text class="meal-icon snack">加</text>
						<text class="meal-name">加餐</text>
					</view>
					<view class="meal-time">{{snackRecords[0].time}}</view>
				</view>
				
				<view class="food-list">
					<view 
						class="food-item" 
						v-for="(item, index) in snackRecords" 
						:key="index"
					>
						<image :src="item.food.image || '/static/images/placeholder.png'" mode="aspectFill" class="food-image"></image>
						<view class="food-info">
							<view class="food-name">{{item.food.name}}</view>
							<view class="food-amount">{{item.amount}}{{item.food.unit}}</view>
							<view class="food-nutrition">
								<text class="nutrition-item">{{item.calories}}kcal</text>
								<text class="nutrition-item">碳水{{item.carbs}}g</text>
								<text class="nutrition-item">蛋白质{{item.protein}}g</text>
							</view>
						</view>
						<view class="food-action">
							<view class="delete-btn" @tap.stop="deleteRecord(item)">
								<text class="iconfont icon-delete"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<image src="/static/images/placeholder.png" mode="aspectFit" class="empty-image"></image>
			<view class="empty-text">暂无饮食记录</view>
			<view class="empty-tips">点击右上角"+"添加记录</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted, watch } from 'vue'
	import { getDietRecords, getDietStats, deleteDietRecord } from '@/common/api/diet.js'
	
	// 日期
	const date = ref('')
	// 餐次类型：all(全部), breakfast(早餐), lunch(午餐), dinner(晚餐), snack(加餐)
	const mealType = ref('all')
	// 饮食记录
	const dietRecords = ref([])
	// 饮食统计
	const dietStats = ref({
		calories: 0,
		carbs: 0,
		protein: 0,
		fat: 0
	})
	
	// 日期范围
	const startDate = computed(() => {
		const now = new Date()
		const year = now.getFullYear()
		const month = (now.getMonth() + 1).toString().padStart(2, '0')
		const day = now.getDate().toString().padStart(2, '0')
		return `${year - 1}-${month}-${day}`
	})
	
	const endDate = computed(() => {
		const now = new Date()
		const year = now.getFullYear()
		const month = (now.getMonth() + 1).toString().padStart(2, '0')
		const day = now.getDate().toString().padStart(2, '0')
		return `${year}-${month}-${day}`
	})
	
	// 格式化日期显示
	const formattedDate = computed(() => {
		if (!date.value) return ''
		
		const today = new Date()
		const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`
		
		const yesterday = new Date(today)
		yesterday.setDate(yesterday.getDate() - 1)
		const yesterdayStr = `${yesterday.getFullYear()}-${(yesterday.getMonth() + 1).toString().padStart(2, '0')}-${yesterday.getDate().toString().padStart(2, '0')}`
		
		if (date.value === todayStr) {
			return '今天'
		} else if (date.value === yesterdayStr) {
			return '昨天'
		} else {
			const dateParts = date.value.split('-')
			return `${dateParts[1]}月${dateParts[2]}日`
		}
	})
	
	// 按餐次分组的记录
	const breakfastRecords = computed(() => {
		return dietRecords.value.filter(item => item.mealType === 'breakfast')
	})
	
	const lunchRecords = computed(() => {
		return dietRecords.value.filter(item => item.mealType === 'lunch')
	})
	
	const dinnerRecords = computed(() => {
		return dietRecords.value.filter(item => item.mealType === 'dinner')
	})
	
	const snackRecords = computed(() => {
		return dietRecords.value.filter(item => item.mealType === 'snack')
	})
	
	// 获取URL参数
	onMounted(() => {
		const query = uni.getSystemInfoSync().platform === 'mp-weixin' ? 
			getCurrentPages()[getCurrentPages().length - 1].options : 
			uni.getLaunchOptionsSync().query
		
		// 设置默认日期为今天
		const now = new Date()
		const year = now.getFullYear()
		const month = (now.getMonth() + 1).toString().padStart(2, '0')
		const day = now.getDate().toString().padStart(2, '0')
		const today = `${year}-${month}-${day}`
		
		if (query && query.date) {
			date.value = query.date
		} else {
			date.value = today
		}
		
		if (query && query.mealType) {
			mealType.value = query.mealType
		}
		
		loadData()
	})
	
	// 监听日期和餐次变化
	watch([date, mealType], () => {
		loadData()
	})
	
	// 加载数据
	const loadData = async () => {
		uni.showLoading({
			title: '加载中...'
		})
		
		try {
			await Promise.all([
				loadDietRecords(),
				loadDietStats()
			])
		} catch (e) {
			console.error('加载数据失败:', e)
		} finally {
			uni.hideLoading()
		}
	}
	
	// 加载饮食记录
	const loadDietRecords = async () => {
		try {
			const params = {
				date: date.value
			}
			
			if (mealType.value !== 'all') {
				params.mealType = mealType.value
			}
			
			const res = await getDietRecords(params)
			
			if (res.code === 0) {
				dietRecords.value = res.data
			} else {
				uni.showToast({
					title: res.message || '加载失败',
					icon: 'none'
				})
			}
		} catch (e) {
			console.error('加载饮食记录失败:', e)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		}
	}
	
	// 加载饮食统计
	const loadDietStats = async () => {
		try {
			const res = await getDietStats({ date: date.value })
			
			if (res.code === 0) {
				dietStats.value = res.data
			} else {
				uni.showToast({
					title: res.message || '加载失败',
					icon: 'none'
				})
			}
		} catch (e) {
			console.error('加载饮食统计失败:', e)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		}
	}
	
	// 日期变化
	const dateChange = (e) => {
		date.value = e.detail.value
	}
	
	// 改变日期
	const changeDate = (offset) => {
		const currentDate = new Date(date.value)
		currentDate.setDate(currentDate.getDate() + offset)
		
		const year = currentDate.getFullYear()
		const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
		const day = currentDate.getDate().toString().padStart(2, '0')
		
		date.value = `${year}-${month}-${day}`
	}
	
	// 选择餐次类型
	const selectMealType = (type) => {
		mealType.value = type
	}
	
	// 添加饮食记录
	const addDietRecord = () => {
		uni.navigateTo({
			url: `/pages/diet/add?date=${date.value}`
		})
	}
	
	// 删除记录
	const deleteRecord = (record) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除这条记录吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						uni.showLoading({
							title: '删除中...'
						})
						
						const result = await deleteDietRecord({ id: record.id })
						
						if (result.code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
							
							// 重新加载数据
							loadData()
						} else {
							uni.showToast({
								title: result.message || '删除失败',
								icon: 'none'
							})
						}
					} catch (e) {
						console.error('删除记录失败:', e)
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					} finally {
						uni.hideLoading()
					}
				}
			}
		})
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss">
	.records-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-bottom: 30rpx;
		
		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background-color: #fff;
			position: sticky;
			top: 0;
			z-index: 100;
			
			.back-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.icon-back {
					font-size: 36rpx;
					color: #333;
				}
			}
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.add-btn {
				width: 60rpx;
				height: 60rpx;
				background-color: #8cc9a1;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				font-size: 32rpx;
			}
		}
		
		.date-selector {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background-color: #fff;
			margin-bottom: 1px;
			
			.date-arrow {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.iconfont {
					font-size: 32rpx;
					color: #666;
				}
			}
			
			.date-picker {
				flex: 1;
				text-align: center;
				
				.date-value {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
			}
		}
		
		.meal-filter {
			display: flex;
			background-color: #fff;
			margin-bottom: 20rpx;
			overflow-x: auto;
			white-space: nowrap;
			
			.filter-item {
				padding: 20rpx 30rpx;
				font-size: 28rpx;
				color: #666;
				position: relative;
				
				&.active {
					color: #8cc9a1;
					font-weight: bold;
					
					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 4rpx;
						background-color: #8cc9a1;
						border-radius: 2rpx;
					}
				}
			}
		}
		
		.nutrition-stats {
			display: flex;
			justify-content: space-between;
			background-color: #fff;
			padding: 20rpx;
			margin-bottom: 20rpx;
			
			.stats-item {
				text-align: center;
				
				.stats-value {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 5rpx;
				}
				
				.stats-label {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
		
		.records-list {
			padding: 0 20rpx;
			
			.meal-section {
				background-color: #fff;
				border-radius: 12rpx;
				margin-bottom: 20rpx;
				overflow: hidden;
				
				.meal-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx;
					border-bottom: 1px solid #f5f5f5;
					
					.meal-title {
						display: flex;
						align-items: center;
						
						.meal-icon {
							width: 40rpx;
							height: 40rpx;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 24rpx;
							color: #fff;
							margin-right: 10rpx;
							
							&.breakfast {
								background-color: #f0ad4e;
							}
							
							&.lunch {
								background-color: #5bc0de;
							}
							
							&.dinner {
								background-color: #d9534f;
							}
							
							&.snack {
								background-color: #8cc9a1;
							}
						}
						
						.meal-name {
							font-size: 28rpx;
							font-weight: bold;
							color: #333;
						}
					}
					
					.meal-time {
						font-size: 24rpx;
						color: #999;
					}
				}
				
				.food-list {
					.food-item {
						display: flex;
						padding: 20rpx;
						border-bottom: 1px solid #f5f5f5;
						
						&:last-child {
							border-bottom: none;
						}
						
						.food-image {
							width: 100rpx;
							height: 100rpx;
							border-radius: 8rpx;
							margin-right: 20rpx;
							background-color: #f9f9f9;
						}
						
						.food-info {
							flex: 1;
							
							.food-name {
								font-size: 28rpx;
								font-weight: bold;
								color: #333;
								margin-bottom: 5rpx;
							}
							
							.food-amount {
								font-size: 24rpx;
								color: #666;
								margin-bottom: 5rpx;
							}
							
							.food-nutrition {
								display: flex;
								
								.nutrition-item {
									font-size: 22rpx;
									color: #999;
									margin-right: 15rpx;
									
									&:last-child {
										margin-right: 0;
									}
								}
							}
						}
						
						.food-action {
							display: flex;
							align-items: center;
							
							.delete-btn {
								width: 60rpx;
								height: 60rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								
								.iconfont {
									font-size: 32rpx;
									color: #999;
								}
							}
						}
					}
				}
			}
		}
		
		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 100rpx 0;
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
			}
			
			.empty-text {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.empty-tips {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
</style> 